<template>
    <div>
        <el-dialog v-model="props.isShow" :title="props.isAdd ? '添加商品规格' : '编辑商品规格'" center :before-close="beforeClose">
            <el-form :model="goodsForm" :rules="rules" ref="goodsRef">
                <el-form-item label="一级分类" :label-width="formLabelWidth" prop="first_cateid">
                    <el-select v-model="goodsForm.first_cateid" placeholder="请选择上级菜单">
                        <el-option label="顶级菜单" :value="0" />
                        <!-- <el-option v-for="item in store.getters['menu/getMenuList']" :key="item.pid" :label="item.title"
                            :value="item.id" /> -->
                    </el-select>
                </el-form-item>

                <el-form-item label="二级分类" :label-width="formLabelWidth" prop="second_cateid">
                    <el-select v-model="goodsForm.second_cateid" placeholder="请选择上级菜单">
                        <el-option label="顶级菜单" :value="0" />
                        <!-- <el-option v-for="item in store.getters['menu/getMenuList']" :key="item.pid" :label="item.title"
                            :value="item.id" /> -->
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
                    <el-input v-model="goodsForm.goodsname" autocomplete="off" />
                </el-form-item>
                <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
                    <el-input v-model="goodsForm.price" autocomplete="off" />
                </el-form-item>
                <el-form-item label="市场价格" :label-width="formLabelWidth" prop="market_price">
                    <el-input v-model="goodsForm.market_price" autocomplete="off" />
                </el-form-item>
                <!-- 图片上传 -->
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload v-model:file-list="fileList" action="#" list-type="picture-card" :auto-upload='false'
                        :limit="1" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>

                    <!-- 预览图片 -->
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>

                </el-form-item>
                <el-form-item label="商品规格" :label-width="formLabelWidth" prop="specsid">
                    <el-select v-model="goodsForm.specsid" placeholder="请选择上级菜单">
                        <el-option label="顶级菜单" :value="0" />
                        <!-- <el-option v-for="item in store.getters['menu/getMenuList']" :key="item.pid" :label="item.title"
                            :value="item.id" /> -->
                    </el-select>
                </el-form-item>

                <el-form-item label="规格属性" :label-width="formLabelWidth" prop="specsattr">
                    <el-select v-model="goodsForm.specsattr" placeholder="请选择上级菜单">
                        <el-option label="顶级菜单" :value="0" />
                        <!-- <el-option v-for="item in store.getters['menu/getMenuList']" :key="item.pid" :label="item.title"
                            :value="item.id" /> -->
                    </el-select>
                </el-form-item>
                <el-form-item label="是否新品" :label-width="formLabelWidth">
                    <el-radio-group v-model="goodsForm.isnew" class="ml-4">
                        <el-radio disabled :label="1" size="small">是</el-radio>
                        <el-radio disabled :label="2" size="small">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否热卖" :label-width="formLabelWidth">
                    <el-radio-group v-model="goodsForm.ishot" class="ml-4">
                        <el-radio disabled :label="1" size="small">是</el-radio>
                        <el-radio disabled :label="2" size="small">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="goodsForm.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <el-input v-model="goodsForm.description" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(goodsRef)">取消</el-button>
                    <el-button type="primary" @click="confirm(goodsRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { goodsadd, goodsedit,goodsinfo } from '../../request/api';
import { defineProps, defineEmits } from 'vue';
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { ref, reactive } from 'vue';
import { Plus, } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';

let store = useStore();
let goodsRef = ref();
let emit = defineEmits(['cancel'])
// 图片列表
const fileList = ref<UploadUserFile[]>([])

// 接收父组件的参数
let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})

let goodsForm = ref({
    first_cateid: '',//一级分类编号
    second_cateid: '',//二级分类编号
    goodsname: '',//商品名称
    price: '',//商品价格
    market_price: '',//市场价格
    img: '',//商品图片（文件）
    description: '',//商品描述
    specsid: '',//商品规格编号
    specsattr: '',//商品规格属性
    isnew: 1,//是否新品     1-是 2-否
    ishot: 1,//是否热卖推荐 1-是 2-否
    status: 1,//状态1正常2禁用
})

const rules = reactive<FormRules>({
    first_cateid: [
        { required: true, message: "请选择一级分类名称", trigger: "change" },
    ],
    second_cateid: [
        { required: true, message: "请选择二级分类名称", trigger: "blur" },
    ],
    goodsname: [
        { required: true, message: "请输入商品分类名称", trigger: "blur" },
        { min: 1, max: 8, message: "长度在 1 到 8 个字符", trigger: "blur" },
    ],
    price: [
        { required: true, message: "请输入价格", trigger: "blur" },
        { min: 1, max: 8, message: "长度在 1 到 8 个字符", trigger: "blur" },
    ],
    market_price: [
        { required: true, message: "请输入市场价格", trigger: "blur" },
        { min: 1, max: 8, message: "长度在 1 到 8 个字符", trigger: "blur" },
    ],
    specsid: [
        { required: true, message: "请选择商品规格", trigger: "change" },
    ],
    specsattr: [
        { required: true, message: "请选择商品属性 ", trigger: "blur" },
    ],
})
const formLabelWidth = '120px';

//  点击x号关闭弹窗
const beforeClose = (done: any) => {
    done();
    cancel(goodsRef.value)
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

// 点击取消
const cancel = (formEl: FormInstance | undefined) => {
    emit('cancel', false)
    if (!formEl) return;
    goodsForm.value = {
        first_cateid: '',//一级分类编号
        second_cateid: '',//二级分类编号
        goodsname: '',//商品名称
        price: '',//商品价格
        market_price: '',//市场价格
        img: '',//商品图片（文件）
        description: '',//商品描述
        specsid: '',//商品规格编号
        specsattr: '',//商品规格属性
        isnew: 1,//是否新品     1-是 2-否
        ishot: 1,//是否热卖推荐 1-是 2-否
        status: 1,//状态1正常2禁用
    }

    // 清空规则
    formEl.resetFields();

}

let newId = 0;
// 数据回显
const lookup = (id: any) => {
    // console.log(id);
    goodsinfo({ id }).then((res) => {
        // if (res.code == 200) {
        //     goodsForm.value = res.list
        //     newId = id
        //     //图片回显
        //     fileList.value = goodsForm.value.img ? [{ url: goodsForm.value.img }] : []
        //     // 由于属性返回字符串，UI库仅支持数组格式
        //     console.log(goodsForm.value.specsattr, 333);
        //     goodsForm.value.specsattr = goodsForm.value.specsattr.split(',');
        //     //重新触发change事件实现二级联动 不触发导致二级回显是value值
        //     changeCate(true)
        //     changeSpecs(true)
        // }
    })
}
// 点击确定
const confirm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate(val => {
        // console.log(val);
        // console.log(goodsForm);
        if (val) {
            console.log(val);

            if (props.isAdd) {
                console.log(1);
                // 添加
                goodsadd(goodsForm.value).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        //调用列表
                        store.dispatch('goods/getgoodslist')
                        store.dispatch('goods/getcount')//获取总条数
                        //隐藏弹框并清空
                        cancel(goodsRef.value)
                        //提示
                        ElMessage.success(res.msg)
                    }

                })
            } else {
                //编辑
                goodsedit({ ...goodsForm.value, id: newId }).then(res => {
                    if (res.code == 200) {
                        //调用列表
                        store.dispatch('goods/getgoodslist')
                        store.dispatch('goods/getcount')//获取总条数
                        //隐藏弹框并清空
                        cancel(goodsRef.value)
                        //提示
                        ElMessage.success(res.msg)
                    } else {
                        //提示
                        ElMessage.error(res.msg)
                    }

                })
            }
        }

    })
}
</script>
<style scoped lang='less'></style>